<?php
/**
 * @link http://framework.zend.com/manual/en/zend.form.elements.html
 */
class Areal_Validate_UniqueUserEmail extends Zend_Validate_Abstract
{
    const NOT_UNIQUE = 'notUnique';

    protected $_messageTemplates = array(
        self::NOT_UNIQUE => 'User with such email already exists'
    );

    public function isValid($value, $context = null)
    {
        $value = (string) $value;
        $this->_setValue($value);
        
        $q = Doctrine_Query::create()
            ->select('u.email, u.password, u.id')
            ->from('Default_Model_User u')
            ->where('u.email = ?')
            ->limit(1);
        $user = $q->fetchOne(array($value));

        if ($user) {
            if(isset($user->id) && isset($context['id']) && $user['id']==$context['id']) return true;

            //Zend_Debug::dump($context); exit();
            $this->_error(self::NOT_UNIQUE);
            return false;
        }

        return true;        
    }
}